package com.zp.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.base.api.entity.AdministrationDict;
import com.zp.base.entity.bo.AdministrationDictBo;
import com.zp.base.entity.vo.AdministrationDictVo;
import com.zp.base.mapper.AdministrationDictMapper;
import com.zp.base.service.IAdministrationDictService;
import com.zp.common.core.constant.UserConstants;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.common.satoken.utils.LoginHelper;
import com.zp.system.api.RemoteBaseDictDataService;
import com.zp.system.api.entity.LoginUser;
import com.zp.system.api.entity.SysBaseDictData;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用药途径Service业务层处理
 *
 * @author zhang peng
 * @date 2023-01-03
 */
@RequiredArgsConstructor
@Service
public class AdministrationDictServiceImpl implements IAdministrationDictService {

    private final AdministrationDictMapper baseMapper;

    @DubboReference
    private RemoteBaseDictDataService remoteBaseDictDataService;

    /**
     * 查询用药途径
     */
    @Override
    public AdministrationDictVo queryById (String id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询用药途径列表(分页)
     */
    @Override
    public TableDataInfo<AdministrationDictVo> queryPageList (AdministrationDictBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AdministrationDict> lqw = buildQueryWrapper(bo);
        Page<AdministrationDictVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用药途径列表(不分页)
     */
    @Override
    public List<AdministrationDictVo> queryList (AdministrationDictBo bo) {
        LambdaQueryWrapper<AdministrationDict> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AdministrationDict> buildQueryWrapper (AdministrationDictBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AdministrationDict> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getLabel()), AdministrationDict::getLabel, bo.getLabel());
        lqw.eq(AdministrationDict::getOrgId, bo.getOrgId());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), AdministrationDict::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getValue()), AdministrationDict::getValue, bo.getValue());
        lqw.eq(bo.getSort() != null, AdministrationDict::getSort, bo.getSort());
        lqw.eq(StringUtils.isNotBlank(bo.getOutpOrInp()), AdministrationDict::getOutpOrInp, bo.getOutpOrInp());
        lqw.eq(bo.getCreateTime() != null, AdministrationDict::getCreateTime, bo.getCreateTime());
        lqw.eq(bo.getUpdateTime() != null, AdministrationDict::getUpdateTime, bo.getUpdateTime());
        lqw.orderByAsc(AdministrationDict::getSort);
        return lqw;
    }

    /**
     * 新增用药途径
     */
    @Override
    public Boolean insertByBo (AdministrationDictBo bo) {
        AdministrationDict add = BeanUtil.toBean(bo, AdministrationDict.class);
        LoginUser loginUser = LoginHelper.getLoginUser();
        validEntityBeforeSave(add);
        add.setDelFlag("0");
        add.setCreateBy(loginUser.getUsername());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 校验用药途径值是否唯一
     *
     * @param bo 用药途径
     * @return 结果
     */
    @Override
    public String checkAdministrationDictUnique (AdministrationDictBo bo) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<AdministrationDict>()
                .eq(AdministrationDict::getValue, bo.getValue())
                .ne(ObjectUtil.isNotNull(bo.getId()), AdministrationDict::getId, bo.getId())
        );
        if (exist) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 修改用药途径
     */
    @Override
    public Boolean updateByBo (AdministrationDictBo bo) {
        AdministrationDict update = BeanUtil.toBean(bo, AdministrationDict.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave (AdministrationDict entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用药途径
     */
    @Override
    public Boolean deleteWithValidByIds (Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    /**
     * 查询系统平台字典列表(业务字典中不存在数据)
     *
     * @param bo
     * @return
     */
    @Override
    public List<SysBaseDictData> listNotExistBaseData (AdministrationDictBo bo) {
        AdministrationDict administrationDict = new AdministrationDict();
        administrationDict.setOrgId(bo.getOrgId());
        administrationDict.setType(bo.getType());
        List<AdministrationDict> administrationDictList = selectAdministrationDictList(administrationDict);
        List<String> collect = administrationDictList.stream().map(e -> e.getValue()).distinct().collect(Collectors.toList());
        return remoteBaseDictDataService.listNotExistBaseData(bo.getType(), collect);
    }


    /**
     * 根据orgId、type查询已添加的用药途径
     *
     * @param administrationDict
     * @return
     */
    public List<AdministrationDict> selectAdministrationDictList (AdministrationDict administrationDict) {
        List<AdministrationDict> administrationDictList = baseMapper.selectList(Wrappers.<AdministrationDict>lambdaQuery()
                .eq(StringUtils.isNotEmpty(administrationDict.getOrgId()), AdministrationDict::getOrgId, administrationDict.getOrgId())
                .eq(StringUtils.isNotEmpty(administrationDict.getType()), AdministrationDict::getType, administrationDict.getType())
        );
        return administrationDictList;
    }

    /**
     * 批量新增勾选的字典值
     *
     * @param bo
     * @return
     */
    @Override
    public Boolean saveBatchAdministrationDictInData (AdministrationDictBo bo) {
        List<AdministrationDict> administrationDictList = new ArrayList<>();
        // 根据字典id查询存在的字典
        List<SysBaseDictData> baseDictDataList = remoteBaseDictDataService.selectExistBaseData(bo.getCheckList());
        if (CollectionUtil.isNotEmpty(baseDictDataList)) {
            baseDictDataList.forEach(item -> {
                AdministrationDict administrationDict = new AdministrationDict();
                BeanUtil.copyProperties(item, administrationDict);
                administrationDict.setOrgId(bo.getOrgId());
                administrationDictList.add(administrationDict);
            });
            baseMapper.insertBatch(administrationDictList);
        }
        return true;
    }
}
